/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    FlatList,
    Image,
    ListView,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';

import Navigation from "../../../custom/Navigation";
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import OrderDetail from "./OrderDetail";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import ModalBottomUtils from "../../../utils/ModalBottomUtils";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import GoodsIsBuyPage from "../../common/GoodsIsBuyPage";
import {DATE_DATA} from '../../../res/json/monthsJson'
import ModalListUtils from "../../../utils/ModalListUtils";

let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
let modalItemIndex = "0";
let selectTime = "0";
export default class OrdersPage extends Component {
    constructor(props) {
        super(props);

        this.state = {
            dataSource: [],
            allDataSource: [],
            modalDataSource: [],
            showLoading: true,
            modalListVisible: false,
            modalDialog: false,
            currency_code: '',
        };
        this.iparNetwork = new IparNetwork();
        this.statusTypes = [I18n.t('default.all'), I18n.t('default.paid'), I18n.t('default.shipped'), I18n.t('default.return'), I18n.t('default.completed')];
    }


    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {
        /*pv*/
        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                this.setState({
                    currency_code: JSON.parse(result).currency_code,
                });
            });

        /**
         * 如果子账号的话获取props的
         */
        this.userId = this.props.userId;
        if (this.userId) {
            this.getOrderInfo('user_id=' + this.userId);
        } else {
            CommonUtils.getAcyncInfo('userInfo')
                .then((result) => {
                    this.main_user_id = JSON.parse(result).main_user_id;
                    this.getOrderInfo('main_user_id=' + this.main_user_id);
                });
        }
    }


    /*
    *网络请求
    *
    * 获取用户详细信息
    */
    getOrderInfo(userId) {
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'listOrder?', userId)
            .then((result) => {
                console.log(result);
                this.setState({showLoading: false});
                if (result.code === 200) {
                    this.setState({
                        dataSource: result.data,
                        allDataSource: result.data,
                    });
                }
            })
            .catch((error) => {
                this.setState({showLoading: false});
                console.log(error)
            })
    }

    /*status type*/
    getOrderStatus(index, orsersData) {
        let orderStatus = [];
        if (index !== "0") {
            for (let i = 0; i < orsersData.length; i++) {
                let isSort = false;
                let datum = orsersData[i];
                switch (index) {
                    case "1":
                        isSort = datum.order_status >= 2;
                        break;
                    case "2":
                        isSort = datum.order_status === 12 || datum.order_status === 29 || datum.order_status === 88;
                        break;
                    case "3":
                        isSort = datum.order_status >= 21 && datum.order_status <= 28 || datum.order_status === 88;
                        break;
                    case "4":
                        isSort = datum.order_status === 88;
                        break;
                }
                if (isSort) {
                    orderStatus.push(datum);
                }
            }
        } else {
            orderStatus = orsersData;
        }

        this.setState({
            dataSource: orderStatus,
            allDataSource: orsersData,
        });
    }

    /*modalBottom 关*/
    hiddenDialog() {
        this.setState({modalDialog: false})
    }

    render() {

        // console.log(this.state.dataSource);
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        let navigator = this.props.navigator;

                        if (this.props.userId) {
                            navigator.pop()
                        } else {
                            navigator.popToTop()
                        }
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />

                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.showLoading}
                            onRefresh={() => {
                            }}
                        />
                    }
                >
                    <View style={[StyleUtils.flex, {padding: 16}]}>
                        {ViewUtils.getTitleView(I18n.t('default.myOrders'), I18n.t('default.orderTitle'))}


                        <View style={[StyleUtils.rowDirection, {marginBottom: 16}]}>
                            {ViewUtils.getButtunMenu(this.state.selectYear|| I18n.t('default.year'), () => {

                                let yearData = [];
                                for (let i = 2018; i < DATE_DATA.year; i++) {
                                    yearData.push(i + 1);
                                }

                                this.setState({
                                    modalListData: yearData,
                                    modalListVisible: true,
                                })
                            }, {flex: 1})}
                            {ViewUtils.getButtunMenu(this.selectMonths||I18n.t('default.month'), () => {
                                this.setState({
                                    modalDialog: true,
                                    modalDataSource: new CommonUtils().getMonthsData(),
                                    modalTypeIsTime: true,
                                    modalTypeIsYear: false,
                                })
                            }, {flex: 1})}
                        </View>


                        {/*订单状态*/}
                        {ViewUtils.getButtunMenu(I18n.t('default.selectOrderType'), () => {
                            this.setState({
                                modalDialog: true,
                                modalDataSource: this.statusTypes,
                                modalTypeIsTime: false,
                                modalTypeIsYear: false,
                            })
                        })}

                        <View style={StyleUtils.lineStyle}/>
                        <View>
                            {/*//默认显示tabText*/}
                            {ViewUtils.getDefaultTab([I18n.t('default.orderNo'), I18n.t('default.amount'), I18n.t('default.status')], '', '', {height: 50}, StyleUtils.defaultTabTv)}
                        </View>


                        <ListView
                            dataSource={ds.cloneWithRows(this.state.dataSource)}
                            renderRow={this.renderRow.bind(this)}/>


                    </View>
                </ScrollView>


                {/***pv and bv*/}
                {this.props.moneyType && <View style={[{padding: 20, paddingBottom: 0}]}>
                    {ViewUtils.getButton(I18n.t('default.keepShopping'), () => {
                        if (this.props.moneyType === 'BV') {
                            this.props.navigator.push({
                                component: GoodsIsBuyPage,
                                name: 'GoodsIsBuyPage',
                                params: {
                                    type: 'bv_list',
                                }
                            })
                        } else {
                            this.props.navigator.popToTop();
                            DeviceEventEmitter.emit('goToPage', 0);
                        }
                    })}
                </View>}

                <ModalListUtils
                    close={() => {
                        this.setState({
                            modalListVisible: false
                        })
                    }}
                    onPress={(index, text) => {
                        let param = this.getSETime(text, this.selectMonths);
                        this.setState({
                            selectYear: text+'',
                            modalListVisible: false
                        });
                        this.getOrderInfo('user_id=' + this.userId + param);
                    }}
                    visible={this.state.modalListVisible}
                    dataSource={ds.cloneWithRows(this.state.modalListData || [])}
                />

                <ModalBottomUtils
                    visible={this.state.modalDialog}
                    dataSource={ds.cloneWithRows(this.state.modalDataSource || [])}
                    requestClose={this.hiddenDialog.bind(this)}
                    renderRow={this.modalRow.bind(this)}
                    title={I18n.t('default.selectOrderType')}
                />
            </View>)


    }


    /*list RenderRow*/
    renderRow(rowData, sectionID, rowID) {
        let money = rowData.full_order_amount;
        let currency_code = this.state.currency_code;

        let moneyType = this.props.moneyType;
        if (moneyType) {
            money = moneyType === 'BV' ? rowData.bbv_amount : rowData.goods_amount;
            currency_code = ' ' + moneyType;
        }

        return ViewUtils.getDefaultTab([rowData.order_sn, (money || 0).toFixed(0) + currency_code, new CommonUtils().orderStatus(rowData.order_status, rowData.return_type)], () => {
            this.props.navigator.push({
                component: OrderDetail,
                params: {
                    orderData: rowData,
                    ordersData: this.state.dataSource,
                    callBack: (orderData) => {


                        let allDataSource = this.state.allDataSource;

                        for (let i = 0, len = allDataSource.length; i < len; i++) {
                            if (allDataSource[i].order_id === orderData.order_id) {
                                allDataSource[i] = orderData;
                            }
                        }
                        this.getOrderStatus(modalItemIndex + "", allDataSource)
                    }
                },
            })
        }, require('../../../res/images/ic_right_more.png'))
    }

    /*modalBottom list renderRow*/
    modalRow(rowData, sectionID, rowID) {

        const {modalTypeIsTime} = this.state;

        let text = rowData;

        if (modalTypeIsTime) {
            text = rowData.name;
        }

        let selectindex = modalItemIndex;
        if (modalTypeIsTime)
            selectindex = selectTime;
        return (<TouchableOpacity
                activeOpacity={0.5}
                onPress={() => {
                    this.modalDialogItemClick(rowData, rowID);
                    if (!modalTypeIsTime)
                        modalItemIndex = rowID + "";
                    else
                        selectTime = rowID + '';
                }}
                style={[StyleUtils.listItem, StyleUtils.center, StyleUtils.rowDirection]}
            >
                <Text
                    style={[StyleUtils.flex, StyleUtils.smallFont, {fontSize: 16, color: 'black'}]}>{text}</Text>
                <Image
                    source={selectindex + "" == rowID + "" ? require('../../../res/images/ic_selected_in.png')
                        : require('../../../res/images/ic_selected.png')}
                    style={{width: 18, height: 18}}/>
            </TouchableOpacity>


        )
    }

    /*modalBottom item 点击*/
    modalDialogItemClick(rowData, rowId) {
        this.hiddenDialog();

        const {modalTypeIsTime, selectYear} = this.state;

        if (modalTypeIsTime) {

            let param = '';
            if (rowId != 0) {
                let code = rowData.code;
                this.selectMonths = code+'';
                param = this.getSETime(selectYear || DATE_DATA.year, code);
            } else
                this.selectMonths = rowData.name;
            this.getOrderInfo('user_id=' + this.userId + param);
        } else {
            this.getOrderStatus(rowId, this.state.allDataSource)
        }
    }


    getSETime(year, months) {
        if (!months) return '';
        let startTime = year + '-' + months + '-01';
        let endTime = year + '-' + months + '-31';
        return '&start_time=' + startTime + '&end_time=' + endTime;
    }
}

